var scales = require('../config.json').scales;
var adapter = require('../utils/dataAdatper');

var _cache = [];
var _dictLower = {};
var _scalesMap = {};
var _dictMap = {};

/**
 * @param data 词典数据的json数组
 * */
function init(data) {
  //1. sort data, for index
  _cache = data.slice(0);
  _cache = _cache.sort(function (a, b) {
    return a.word > b.word ? 1 : -1;
  });
  //2. init scales
  for (var i in scales) {
    i !== '0' && (_scalesMap[i] = []);
  }
  //3. init data and indexes
  for (var j = 0; j < _cache.length; j++) {
    _dictLower[_cache[j].word.toLowerCase()] = _cache[j];
    _dictMap[_cache[j].word] = j;
    if (_cache[j].scale !== 0) {
      var current = +_cache[j].scale;
      if (isNaN(current)) current = 0;
      while (_scalesMap[current]) {
        _scalesMap[current++].push(_cache[j].word);
      }
    }
  }
}

/**
 * @param condition.word 要查询的单词
 * @param condition.segment 要查询的片段
 * @param condition.scales 要查询的所属范围, 逗号分隔
 * @param condition.pageIndex 页码
 * @param condition.pageSize 页面单词数
 * @param condition.type detail|phonetic|explains|scale其中之一
 * */
function find(condition) {
  !condition.type && (condition.type = 'detail');
  if (condition.word) {
    var idx = _dictMap[condition.word];
    if(typeof idx === "undefined") return [];
    return adapter(_cache[idx], condition.type);
  }

  var temp = _cache.slice(0);
  var result = [];
  var tmpResult = [];
  if (condition.segment) {
    var reg = new RegExp(condition.segment, 'i');
    for (var i = 0; i < temp.length; i++) {
      if (temp[i].word.search(reg) !== -1) {
        result.push(temp[i]);
      }
    }
  } else {
    result = temp;
  }
  if (condition.scales) {
    tmpResult = [];
    for (i = 0; i < result.length; i++) {
      if (condition.scales.indexOf('' + result[i].scale) !== -1) {
        tmpResult.push(result[i]);
      }
    }
    result = tmpResult;
  }

  var pIndex = +condition.pageIndex;
  var pSize = +condition.pageSize;
  if (!isNaN(pIndex) && !isNaN(pSize)) {
    tmpResult = [];
    for (i = (pIndex - 1) * pSize; i < pIndex * pSize; i++) {
      result[i] && tmpResult.push(result[i]);
    }
    result = tmpResult;
  }

  for (i = 0; i < result.length; i++) {
    result[i] = adapter(result[i], condition.type);
  }
  return result;
}

/**
 * @param word 要更新的词汇
 * @param data 词汇信息
 * */
function update(word, data) {
  var oldInfo = _cache[_dictMap[word]];
  if (oldInfo.scale != data.scale) {
    if (oldInfo.scale != 0) {
      var cursor = -1;
      for (var i = 0; i < _scalesMap[oldInfo.scale].length; i++) {
        if (_scalesMap[oldInfo.scale][i] == word) {
          cursor = i;
          break;
        }
      }
      cursor !== -1 && _scalesMap[oldInfo.scale].splice(cursor, 1);
    }
    if (data.scale != 0) {
      var insertPoint = -1;
      for (var j = 0; j < _scalesMap[data.scale].length; j++) {
        if (_scalesMap[data.scale][j] == word) {
          break;
        }
        if (_scalesMap[data.scale][j] > word) {
          insertPoint = j;
          break;
        }
      }
      if (insertPoint != -1) {
        var part1 = _scalesMap[data.scale].slice(0, insertPoint);
        var part2 = _scalesMap[data.scale].slice(insertPoint);
        part1.push(word);
        _scalesMap[data.scale] = part1.concat(part2);
      }
    }
  }
  _cache[_dictMap[word]] = data;
}

/**
 * @param text 英文文本
 * @param scale 范围
 * */
function filterScaleByText(text, scale) {
  //取词
  var arr = text.match(/[a-zA-Z]+-?[a-zA-Z]+/g);
  //去重
  var temp = {};
  for (var i = 0; i < arr.length; i++) {
    temp[arr[i]] = true;
  }
  arr = [];
  for (var j in temp) {
    arr.push(j);
  }
  return filterScaleByArray(arr, scale);
}

/**
 * @description 核心算法, 最小时间复杂度遍历出超纲词
 * @param arr 单词数组
 * @param scale 范围
 * */
function filterScaleByArray(arr, scale) {
  if (!scales[scale] || arr.length == 0) return [];
  //排序
  arr.sort();
  var outScale = [];
  var src_cursor = 0;
  var target_cursor = 0;
  var target = _scalesMap[scale];
  //双指针归并, 时间复杂度O(m)+O(n)
  while (src_cursor < arr.length) {
    if (arr[src_cursor] < target[target_cursor]) {
      outScale.push(arr[src_cursor]);
      src_cursor++;
      continue;
    }
    if (arr[src_cursor] == target[target_cursor]) {
      src_cursor++;
    }
    target_cursor++;
    //预防词典数据不全导致无法退出循环
    if (target_cursor == target.length) {
      for (var i = src_cursor; i < arr.length; i++) {
        outScale.push(arr[i]);
      }
      break;
    }
  }
  return outScale;
}

/**
 * @description 找到音标
 * @param text 单词数组
 * */
function phonetic(text) {
  text = text.toLowerCase();
  var cursor = 0;
  var result = [];
  while(cursor < text.length) {
    var code = text[cursor].charCodeAt(0);
    if(code < 123 && code > 96 || code == 45) {
      var obj = { index: cursor, size: 0, phonetic: null };
      var word = '';
      while(cursor < text.length) {
        code = text[cursor].charCodeAt(0);
        if(code > 123 || code < 97 && code != 45) {
          break;
        }
        word += text[cursor];
        obj.size ++;
        cursor++;
      }
      if(_dictLower[word] && _dictLower[word].phonetic)
        obj.phonetic = _dictLower[word].phonetic;
      result.push(obj);
    } else {
      cursor++;
    }
  }
  return result;
}

exports.dict = function () {
  return _cache;
};
exports.init = init;
exports.query = find;
exports.save = update;
exports.filterScaleByText = filterScaleByText;
exports.phonetic = phonetic;